package com.cpit.platform.common.dao;

import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/** 
 * 逻辑条件表达式 用于复杂条件时使用，属性多个条件的and或者OR查询等
 */  
public class LogicalExpression implements Criterion {
	private Criterion[] criterion;  // 逻辑表达式中包含的表达式  
	private Operator operator;      //计算符,and和or

    public LogicalExpression(Criterion[] criterions, Operator operator) {
        this.criterion = criterions;  
        this.operator = operator;  
    }

    public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query,  
            CriteriaBuilder builder) {
        if(operator == null || criterion == null){
            return null;
        }
        List<Predicate> predicates = new ArrayList<Predicate>();  
	    for(int i=0;i<this.criterion.length;i++){
            Predicate predicate = this.criterion[i].toPredicate(root, query, builder);
            if(predicate != null){
	             predicates.add(predicate);
            }
	    }
        switch (operator) {  
        case OR:  
            return builder.or(predicates.toArray(new Predicate[predicates.size()]));  
        case AND:  
            return builder.and(predicates.toArray(new Predicate[predicates.size()]));
        default:  
            return null;  
        }  
    }
}
